package com.android.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spanned;
import android.text.style.ImageSpan;

import com.android.myfirstapps.Item;
import com.sun.cnpi.rss.elements.Rss;
import com.sun.cnpi.rss.parser.RssParser;
import com.sun.cnpi.rss.parser.RssParserException;
import com.sun.cnpi.rss.parser.RssParserFactory;

public class ParseXML {
	
	public List<Item> readRSS(String url){
		List<Item> listeItem = new ArrayList<Item>();
		RssParser parser;
		try {
			parser = RssParserFactory.createDefault();
			Rss rss = parser.parse(new URL(url));
			Collection item = rss.getChannel().getChildren();
			for (Object object : item) {
				if(object instanceof com.sun.cnpi.rss.elements.Item){
					com.sun.cnpi.rss.elements.Item unItem = (com.sun.cnpi.rss.elements.Item)object;
					Spanned span = android.text.Html.fromHtml(unItem.getDescription().getText());
					
					ImageSpan[] tabImageSpan = span.getSpans(0, span.length(), ImageSpan.class);
					String image = "";
					if(tabImageSpan!= null && tabImageSpan.length > 0)
						image = tabImageSpan[0].getSource();
						
					String description = span.toString();
					if(description.contains("\n\n")){
						description = description.split("\n\n")[2];
					}
					listeItem.add(new Item(unItem.getTitle().getText(), description,unItem.getPubDate().getText(),unItem.getLink().getText(),getBitmap(image)));
				}
			}
		} catch (RssParserException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return listeItem;
	}

	/**
	 * 
	 */
	private Bitmap getBitmap(String url) {
		if(null == url || "".equals(url))
			return null;
		
		HttpURLConnection connection;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			return BitmapFactory.decodeStream(input);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * @param fstElmnt
	 */
	private String getElement(Element pere, String nom) {
		Element fils = (Element) pere.getElementsByTagName(nom).item(0);
		return ((Node) fils.getChildNodes().item(0)).getNodeValue();
	}
	
	String removeHTML(String text){
		return text.replaceAll("\\<.*?>","");
	}

}